const express = require('express');
const cors = require('cors');
const compression = require('compression');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const morgan = require('morgan');
const path = require('path');
const fs = require('fs-extra');

// 导入路由
const staticRoutes = require('./routes/static');
const versionRoutes = require('./routes/version');

// 导入中间件
const corsMiddleware = require('./middleware/cors');
const cacheMiddleware = require('./middleware/cache');

// 导入配置
const config = require('./config/server');

const app = express();
const PORT = process.env.PORT || config.port;

// 安全中间件
app.use(helmet({
    contentSecurityPolicy: false, // 允许静态资源加载
    crossOriginEmbedderPolicy: false
}));

// 压缩中间件
app.use(compression());

// 日志中间件
app.use(morgan('combined'));

// CORS中间件
app.use(corsMiddleware);

// 缓存中间件
app.use(cacheMiddleware);

// 请求频率限制
const limiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15分钟
    max: 1000, // 限制每个IP 15分钟内最多1000个请求
    message: {
        error: '请求过于频繁，请稍后再试',
        retryAfter: '15分钟'
    },
    standardHeaders: true,
    legacyHeaders: false
});
app.use('/api/', limiter);

// 静态资源路由
app.use('/static', staticRoutes);

// 版本管理路由
app.use('/api', versionRoutes);

// 根路径 - 提供API信息
app.get('/', (req, res) => {
    res.json({
        name: 'Web Playback Server',
        version: '1.0.0',
        description: 'Static resource server for Web Playback Android app',
        endpoints: {
            static: '/static/{path}',
            version: '/api/version',
            resources: '/api/resources',
            health: '/api/health'
        },
        timestamp: new Date().toISOString()
    });
});

// 健康检查
app.get('/api/health', (req, res) => {
    res.json({
        status: 'healthy',
        timestamp: new Date().toISOString(),
        uptime: process.uptime(),
        memory: process.memoryUsage(),
        version: require('./package.json').version
    });
});

// 404处理
app.use('*', (req, res) => {
    res.status(404).json({
        error: '资源未找到',
        path: req.originalUrl,
        timestamp: new Date().toISOString()
    });
});

// 错误处理中间件
app.use((err, req, res, next) => {
    console.error('服务器错误:', err);
    
    res.status(err.status || 500).json({
        error: process.env.NODE_ENV === 'production' 
            ? '服务器内部错误' 
            : err.message,
        timestamp: new Date().toISOString(),
        ...(process.env.NODE_ENV !== 'production' && { stack: err.stack })
    });
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`🚀 服务器启动成功!`);
    console.log(`📡 端口: ${PORT}`);
    console.log(`🌍 环境: ${process.env.NODE_ENV || 'development'}`);
    console.log(`📁 静态资源目录: ${config.staticPath}`);
    console.log(`🔗 访问地址: http://localhost:${PORT}`);
    console.log(`📋 API文档: http://localhost:${PORT}/api/health`);
});

// 优雅关闭
process.on('SIGTERM', () => {
    console.log('收到SIGTERM信号，正在关闭服务器...');
    process.exit(0);
});

process.on('SIGINT', () => {
    console.log('收到SIGINT信号，正在关闭服务器...');
    process.exit(0);
});

module.exports = app;
